package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.service.*;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

//会员数量统计
@RestController
@RequestMapping("/report")
public class CountController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @Reference
    private IncomeService incomeService;

    @Reference
    private OrderService orderService;

    //会员数量统计 以折线图展示出来
    @RequestMapping("/member/count")
    public Result getMemberReport() {
        try {
            //创建日历对象
            Calendar calendar = Calendar.getInstance();
            //获取当前日期前十二个月得日期
            calendar.add(Calendar.MONTH, -12);

            //创建一个集合封装
            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                //获取当前日期得后一个月的日期
                calendar.add(Calendar.MONTH, 1);
                //将日期添加到集合
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }

            //封装map集合,封装月份和每月的会员数量
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);

            //根据月份统计会员数量
            List<Integer> memberCount = memberService.findMemberCount(months);
            //将数据封装到map集合
            map.put("memberCount", memberCount);
            //调用MessageConstant消息常量: "获取会员统计数据成功"
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用MessageConstant消息常量: "获取会员统计数据失败"
        return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
    }

    //套餐预约统计,以饼图展示出来
    @RequestMapping("/setmeals")
    public Result getSetmealsReport() {
        try {
            //调用service,查询每个体检套餐的预约数量
            List<Map<String, Object>> setmealCount = setmealService.findSetmealOrderedCount();
            //创建一个map集合用来填充饼图参数setmealNames,setmealCount
            Map<String, Object> map = new HashMap<>();
            //遍历setmealsCount集合重新封装成list集合
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> setmealName : setmealCount) {
                //取出name
                String name = (String) setmealName.get("name");
                //把预套餐名字,添加到setmealNames
                setmealNames.add(name);
            }
            //将饼图参数setmealNames,setmealCount封装进map集合
            map.put("setmealNames", setmealNames);  //预约套餐名字
            map.put("setmealCount", setmealCount);  //预约套餐数量
            //调用MessageConstant消息常量: "获取套餐统计数据成功"
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果为空
        //调用MessageConstant消息常量: "获取套餐统计数据失败"
        return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
    }

    //运营数据统计
    @RequestMapping("/business")
    public Result getBusinessReportData(){
        try {
            //调用service层,获取后端信息
            Map<String,Object> result = reportService.getBusinessReportData();
            //调用MessageConstant消息常量: "获取运营统计数据成功"
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //调用MessageConstant消息常量: "获取运营统计数据失败"
        return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }


    //导出运营数据统计
    @RequestMapping("/export/business")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            //调用service层,获取后端信息
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回的数据结果,将数据写入到Excel表中
            String reportDate = (String) result.get("reportDate"); //今天日期
            Integer todayNewMember = (Integer) result.get("todayNewMember"); //新增会员数
            Integer totalMember = (Integer) result.get("totalMember"); //总会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");//本周新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");//本月新增会员数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");//今天预约数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");//今天到诊数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");//本周预约数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");//本周到诊数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");//本月预约数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");//本周到诊数
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");//热门套餐 取前四


            //获取excel表格路径
            Resource resource = new ClassPathResource("static/template/report_template.xlsx");
            String path = resource.getFile().getPath();
            //读取模板文件创建Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(path)));
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取第三行
            XSSFRow row = sheet.getRow(2);
            //获取第六页, 根据模板添加对于数据
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map map : hotSetmeal) {//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");   //指明文件路径
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");  //设置响应头 report.xlsx
            workbook.write(out);  //将文件输出

            out.flush();   //刷新流
            out.close();  //关闭流
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //如果为空
        //调用MessageConstant消息常量: "获取运营统计数据失败"
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL, null);
    }

    //收入统计
    @RequestMapping("/income/count")
    public Result getIncomeCount(){
        try {
            //创建日历对象
            Calendar calendar = Calendar.getInstance();
            //获取当前日期前十二个月得日期
            calendar.add(Calendar.MONTH, -12);

            //创建一个集合封装
            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                //获取当前日期得后一个月的日期
                calendar.add(Calendar.MONTH, 1);
                //将日期添加到集合
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }

            //封装map集合,封装月份和每月的收入数量
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);

            //根据月份统计收入数量
            List<Integer> money = incomeService.findIncomeMoney(months);
            //将数据封装到map集合
            map.put("incomeCount", money);
            return new Result(true, "获取收入统计数据成功", map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,"获取收入统计数据失败");
    }


    //预约/支付统计
    @RequestMapping("/order/count")
    public Result getOrderCount(){
        try {
            //创建日历对象
            Calendar calendar = Calendar.getInstance();
            //获取当前日期前十二个月得日期
            calendar.add(Calendar.MONTH, -12);

            //创建一个集合封装
            List<String> months = new ArrayList<>();
            for (int i = 0; i < 12; i++) {
                //获取当前日期得后一个月的日期
                calendar.add(Calendar.MONTH, 1);
                //将日期添加到集合
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }

            //封装map集合,封装月份和每月的预约,支付数量
            Map<String, Object> map = new HashMap<>();
            map.put("months", months);

            //根据月份统计预约数量
            List<Integer> orderCount = orderService.findOrderCount(months);

            //根据月份统计支付数量
            List<Integer> payCount = orderService.findPayCount(months);

            //将数据封装到map集合
            map.put("orderCount", orderCount); //预约数量
            map.put("payCount",payCount);  //支付数量

            //"查询预约信息成功"
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //"查询预约信息失败"
        return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
    }


}
